// 富文本编辑框 

import React, { Component } from 'react'
import {Editor} from "react-draft-wysiwyg"   // Editor
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import draftToHtml from "draftjs-to-html"  // draft ===> html;
import htmlToDraft from "html-to-draftjs" //  html ===>  draft
import {EditorState,ContentState} from "draft-js"
import "./index.less"


export default class RichEditor extends Component {
    state = {
        editorState:"",  // 状态
        contentState:""  // 内容 
    }
    onEditorStateChange=(editorState)=>{  // 修改编辑框的 state 
        this.setState({
            editorState
        })
    }
    onContentStateChange=(contentState)=>{ // 修改编辑框的 内容   
        this.setState({
            contentState
        })
    }

    componentDidMount(){
        if(!this.props.content){ // 父改子 
            return ;
        }
        
        // 修改  修改数据
        const html = this.props.content; 
        const contentBlock = htmlToDraft(html);
        if (contentBlock) {
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks); // 创建内容从 htmlToDraft
            const editorState = EditorState.createWithContent(contentState);// 创建编辑器状态 
            console.log(editorState)
            this.setState({
                editorState
            })
        }
    }
    render() {
        return (
            <div>
                <Editor
                    editorState={this.state.editorState}
                    toolbarClassName="toolbarClassName" // DIY样式
                    wrapperClassName="wrapperClassName" // DIY样式
                    editorClassName="editorClassName" // DIY样式
                    onEditorStateChange={this.onEditorStateChange}  
                    onContentStateChange={this.onContentStateChange}
                    onBlur={
                        ()=>{
                            // console.log(this.state.contentState)
                            this.props.getContent(draftToHtml(this.state.contentState))  // 子改父 
                        }
                    }
                />
            </div>
        )
    }
}